<template>
  <ele-modal
    form
    :width="600"
    :model-value="modelValue"
    :title="title"
    @update:modelValue="updateModelValue"
  >
    <ele-page>
      <ele-card class="step-card">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="98px">
          <el-form-item label="原因" prop="refund_reject_reason">
            <el-input
              v-model="form.refund_reject_reason"
              style="width: 300px"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :loading="loading" @click="save">
              保存
            </el-button>
          </el-form-item>
        </el-form>
      </ele-card>
    </ele-page>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch } from 'vue';
  import { rejectMallTradeRefund } from '@/api/mall';
  import { EleMessage } from 'ele-admin-plus/es';

  import { useFormData } from '@/utils/use-form-data';

  const emit = defineEmits(['done', 'update:modelValue']);
  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object
  });

  const title = ref('');

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);

  /** 表单数据 */
  const [form, resetFields, assignFields] = useFormData({
    id: 0,
    refund_reject_reason: ''
  });

  const rules = reactive({
    refund_reject_reason: [
      {
        required: true,
        message: '请填写拒绝原因',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  /** 提交 */
  const save = () => {
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      var requestData = Object.assign({}, form);
      requestData.status = 0;
      requestData.trade_id = props.data.trade_id;
      rejectMallTradeRefund(requestData)
        .then(() => {
          loading.value = false;
          EleMessage.success('操作成功');
          updateModelValue(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          console.log(e);
        });
    });
  };

  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        assignFields(props.data);
        title.value =
          '拒绝' +
          props.data.realname +
          props.data.goods_title +
          '的门票退款申请';
      } else {
        resetFields();
        formRef.value?.clearValidate?.();
        console.log('关闭');
      }
    }
  );
</script>
